Bias detection and mitigation in AutoAI¶
This notebook contains the steps and code to demonstrate support of AutoAI experiments with bias detection/mitigation in watsonx.ai service. It introduces commands for data retrieval, training experiments, persisting pipelines, testing pipelines and scoring.
Some familiarity with Python is helpful. This notebook uses Python 3.12.
Learning goals¶
The learning goals of this notebook are:
- Work with watsonx.ai experiment to train AutoAI models with bias detection and mitigation.
- Compare trained models quality and fairness.
Contents¶
This notebook contains the following parts:
1. Set up the environment¶
Before you use the sample code in this notebook, you must perform the following setup tasks:
- Contact with your Cloud Pak for Data administrator and ask them for your account credentials
%pip install -U wget | tail -n 1
%pip install -U autoai-libs | tail -n 1
%pip install -U ibm-watsonx-ai | tail -n 1
%pip install "scikit-learn==1.6.1" | tail -n 1
%pip install -U "lale[fairness]" | tail -n 1
%pip install -U nbformat | tail -n 1
Successfully installed wget-3.2 Successfully installed autoai-libs-3.0.3 Successfully installed ibm-watsonx-ai-1.3.20 Requirement already satisfied: threadpoolctl>=3.1.0 in /opt/user-env/pyt6/lib64/python3.12/site-packages (from scikit-learn==1.6.1) (3.6.0) Successfully installed BlackBoxAuditing-0.1.54 aif360-0.6.1 imbalanced-learn-0.13.0 klepto-0.2.7 liac-arff-2.5.0 mystic-0.4.4 pox-0.3.6 sklearn-compat-0.1.3 Successfully installed fastjsonschema-2.21.1 nbformat-5.10.4
Define credentials¶
Authenticate the watsonx.ai Runtime service on IBM Cloud Pak for Data. You need to provide the admin's username and the platform url.
username = "PASTE YOUR USERNAME HERE"
url = "PASTE THE PLATFORM URL HERE"
Use the admin's api_key to authenticate watsonx.ai Runtime services:
import getpass
from ibm_watsonx_ai import Credentials
credentials = Credentials(
username=username,
api_key=getpass.getpass("Enter your watsonx.ai API key and hit enter: "),
url=url,
instance_id="openshift",
version="5.2",
)
Alternatively you can use the admin's password:
import getpass
from ibm_watsonx_ai import Credentials
if "credentials" not in locals() or not credentials.api_key:
credentials = Credentials(
username=username,
password=getpass.getpass("Enter your watsonx.ai password and hit enter: "),
url=url,
instance_id="openshift",
version="5.2",
)
Enter your watsonx.ai password and hit enter: ········
Create APIClient instance¶
from ibm_watsonx_ai import APIClient
client = APIClient(credentials)
Working with spaces¶
First of all, you need to create a space that will be used for your work. If you do not have space already created, you can use {PLATFORM_URL}/ml-runtime/spaces?context=icp4data to create one.
- Click New Deployment Space
- Create an empty space
- Go to space
Settingstab - Copy
space_idand paste it below
Tip: You can also use SDK to prepare the space for your work. More information can be found here.
Action: Assign space ID below
space_id = "PASTE YOUR SPACE ID HERE"
You can use the list method to print all existing spaces.
client.spaces.list(limit=10)
To be able to interact with all resources available in watsonx.ai, you need to set the space which you will be using.
client.set.default_space(space_id)
'SUCCESS'
Optimizer definition¶
Training data sets¶
Define connection information to training data CSV file.
Download training data from git repository.
import wget
import os
filename = "german_credit_data_biased_training.csv"
url = "https://github.com/IBM/watsonx-ai-samples/raw/master/cpd5.2/data/bias/german_credit_data_biased_training.csv"
if not os.path.isfile(filename):
wget.download(url)
Create data asset¶
asset_details = client.data_assets.create(
"german_credit_data_biased_training.csv", filename
)
asset_details
Creating data asset... SUCCESS
{'metadata': {'space_id': '9c4eb218-96e8-41e0-8cd5-f783504a11ea',
'usage': {'last_updated_at': '2025-05-23T12:42:20Z',
'last_updater_id': '1000331001',
'last_update_time': 1748004140550,
'last_accessed_at': '2025-05-23T12:42:20Z',
'last_access_time': 1748004140550,
'last_accessor_id': '1000331001',
'access_count': 0},
'rov': {'mode': 0,
'collaborator_ids': {},
'member_roles': {'1000331001': {'user_iam_id': '1000331001',
'roles': ['OWNER']}}},
'is_linked_with_sub_container': False,
'name': 'german_credit_data_biased_training.csv',
'description': '',
'asset_type': 'data_asset',
'origin_country': 'us',
'resource_key': 'german_credit_data_biased_training.csv',
'rating': 0.0,
'total_ratings': 0,
'catalog_id': '32c875f2-f104-4801-9d5f-a0987098790c',
'created': 1748004140550,
'created_at': '2025-05-23T12:42:20Z',
'owner_id': '1000331001',
'size': 0,
'version': 2.0,
'asset_state': 'available',
'asset_attributes': ['data_asset'],
'asset_id': 'f487bd4f-6539-4004-8d7f-c7a82415807b',
'asset_category': 'USER',
'creator_id': '1000331001',
'is_branched': True,
'guid': 'f487bd4f-6539-4004-8d7f-c7a82415807b',
'href': '/v2/assets/f487bd4f-6539-4004-8d7f-c7a82415807b?space_id=9c4eb218-96e8-41e0-8cd5-f783504a11ea',
'last_updated_at': '2025-05-23T12:42:20Z'},
'entity': {'data_asset': {'mime_type': 'text/csv'}}}
client.data_assets.get_id(asset_details)
'f487bd4f-6539-4004-8d7f-c7a82415807b'
from ibm_watsonx_ai.helpers import DataConnection
german_credit_risk = DataConnection(
data_asset_id=client.data_assets.get_id(asset_details)
)
training_data_reference = [german_credit_risk]
Bias detection and mitigation¶
Terms and definitions:¶
Fairness Attribute - Bias or fairness is typically measured using some fairness attribute such as Gender, Ethnicity, Age, etc.
Monitored/Reference Group - Monitored group are those values of fairness attribute for which we want to measure bias. The rest of the values of the fairness attributes are called as reference group. In case of Fairness Attribute=Gender, if we are trying to measure bias against females, then Monitored group is “Female” and Reference group is “Male”.
Favourable/Unfavourable outcome - An important concept in bias detection is that of favourable and unfavourable outcome of the model. E.g., Claim approved can be considered as a favourable outcome and Claim denied can be considered as an unfavourable outcome.
Disparate Impact - metric used to measure bias (computed as the ratio of percentage of favourable outcome for the monitored group to the percentage of favourable outcome for the reference group). Bias is said to exist if the disparate impact value is below some threshold.
Optimizer configuration¶
Provide input information for AutoAI optimizer:
name- experiment nameprediction_type- type of the problemprediction_column- target column namefairness_info- bias detection configurationscoring-accuracy_and_disparate_impactcombined optimization metric for both accuracy and fairness. For regression learning problem ther2_and_disparate_impactmetric is supported (combines r2 and fairness).
fairness_info definition:¶
protected_attributes(list of dicts) – subset of features for which fairness calculation is desired.feature- name of feature for whichreference_groupandmonitored_groupare specified.reference_groupandmonitored_group- monitored group are those values of fairness attribute for which we want to measure bias. The rest of the values of the fairness attribute are reference group.
favorable_labelsandunfavorable_labels– label values which are considered favorable (i.e. “positive”).unfavorable_labelsare required when prediction type is regression.
Examples of supported configuration:
fairness_info = {
"protected_attributes": [
{"feature": "Age", "reference_group": [[26, 26], [30, 75]],
"monitored_group": [[18, 25], [27, 29]]}
],
"favorable_labels": ["No Risk"]
}
fairness_info = {
"protected_attributes": [
{"feature": "sex", "reference_group": ['male', 'not specified'],
"monitored_group": ['female']},
{"feature": "age", "reference_group": [[26, 100]], "monitored_group": [[18, 25], [27, 29]]}
],
"favorable_labels": [[5000.01, 9000]],
"unfavorable_labels": [[0, 5000], [9000, 1000000]]
}
fairness_info = {
"protected_attributes": [
{"feature": "Sex", "reference_group": ["male"], "monitored_group": ["female"]},
{
"feature": "Age",
"reference_group": [[26, 75]],
"monitored_group": [[18, 25]],
},
],
"favorable_labels": ["No Risk"],
"unfavorable_labels": ["Risk"],
}
from ibm_watsonx_ai.experiment import AutoAI
experiment = AutoAI(credentials, space_id=space_id)
pipeline_optimizer = experiment.optimizer(
name="Credit Risk Prediction and bias detection - AutoAI",
prediction_type=AutoAI.PredictionType.BINARY,
prediction_column="Risk",
scoring="accuracy_and_disparate_impact",
fairness_info=fairness_info,
max_number_of_estimators=1,
retrain_on_holdout=False,
include_only_estimators=["XGBClassifier"],
)
Experiment run¶
Call the fit() method to trigger the AutoAI experiment. You can either use interactive mode (synchronous job) or background mode (asychronous job) by specifying background_model=True.
run_details = pipeline_optimizer.fit(
training_data_reference=training_data_reference, background_mode=False
)
Training job a3ce47c9-3da6-481f-9a71-59775dae5ecc completed: 100%|████████| [01:53<00:00, 1.14s/it]
You can use the get_run_status() method to monitor AutoAI jobs in background mode.
Get selected pipeline model¶
Download and reconstruct a scikit-learn pipeline model object from the AutoAI training job.
experiment_summary = pipeline_optimizer.summary()
experiment_summary.head()
| Enhancements | Estimator | training_accuracy_and_disparate_impact_(optimized) | training_disparate_impact_Sex | training_roc_auc | holdout_disparate_impact_Sex | holdout_average_precision | holdout_log_loss | holdout_roc_auc | training_disparate_impact | ... | holdout_accuracy | holdout_balanced_accuracy | training_recall | holdout_f1 | training_accuracy | holdout_disparate_impact | training_balanced_accuracy | holdout_disparate_impact_Age | training_f1 | training_disparate_impact_Age | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Pipeline Name | |||||||||||||||||||||
| Pipeline_1 | XGBClassifier | 0.676887 | 1.009581 | 0.846120 | 1.046499 | 0.480936 | 0.419151 | 0.855620 | 1.825512 | ... | 0.811623 | 0.754275 | 0.894970 | 0.867606 | 0.796567 | 1.431694 | 0.748223 | 1.426056 | 0.853965 | 2.329145 | |
| Pipeline_2 | HPO | XGBClassifier | 0.676887 | 1.009581 | 0.846120 | 1.046499 | 0.480936 | 0.419151 | 0.855620 | 1.825512 | ... | 0.811623 | 0.754275 | 0.894970 | 0.867606 | 0.796567 | 1.431694 | 0.748223 | 1.426056 | 0.853965 | 2.329145 |
| Pipeline_3 | HPO, FE | XGBClassifier | 0.681126 | 1.009843 | 0.846576 | 1.057825 | 0.481095 | 0.416944 | 0.855187 | 1.787199 | ... | 0.809619 | 0.755745 | 0.892283 | 0.865248 | 0.795004 | 1.463687 | 0.747200 | 1.451613 | 0.852646 | 2.286728 |
| Pipeline_4 | HPO, FE, HPO | XGBClassifier | 0.681126 | 1.009843 | 0.846576 | 1.057825 | 0.481095 | 0.416944 | 0.855187 | 1.787199 | ... | 0.809619 | 0.755745 | 0.892283 | 0.865248 | 0.795004 | 1.463687 | 0.747200 | 1.451613 | 0.852646 | 2.286728 |
| Pipeline_5 | HPO, FE, HPO, Ensemble | BatchedTreeEnsembleClassifier(XGBClassifier) | 0.681126 | 1.009843 | 0.846576 | 1.057825 | 0.481095 | 0.416944 | 0.855187 | 1.787199 | ... | 0.809619 | 0.755745 | 0.892283 | 0.865248 | 0.795004 | 1.463687 | 0.747200 | 1.451613 | 0.852646 | 2.286728 |
5 rows × 26 columns
Visualize pipeline¶
pipeline_name = experiment_summary.index[
experiment_summary.holdout_disparate_impact.argmax()
]
best_pipeline = pipeline_optimizer.get_pipeline(pipeline_name=pipeline_name)
best_pipeline.export_to_sklearn_pipeline()
Pipeline(steps=[('featureunion',
FeatureUnion(transformer_list=[('float32_transform_140705276704720',
Pipeline(steps=[('numpycolumnselector',
NumpyColumnSelector(columns=[0,
1,
2,
3,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19])),
('compressstrings',
CompressStrings(compress_type='hash',
dtypes_list=['char_str',
'float_int_num',
'char_str',
'char_str',
'char_str',
'c...
feature_types=None, gamma=None, gpu_id=None,
grow_policy=None, importance_type='gain',
interaction_constraints=None, learning_rate=None,
max_bin=None, max_cat_threshold=None,
max_cat_to_onehot=None, max_delta_step=None,
max_depth=3, max_leaves=None, min_child_weight=1,
missing=nan, monotone_constraints=None,
multi_strategy=None, n_estimators=100, n_jobs=4,
nthread=None, ...))])In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Pipeline(steps=[('featureunion',
FeatureUnion(transformer_list=[('float32_transform_140705276704720',
Pipeline(steps=[('numpycolumnselector',
NumpyColumnSelector(columns=[0,
1,
2,
3,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19])),
('compressstrings',
CompressStrings(compress_type='hash',
dtypes_list=['char_str',
'float_int_num',
'char_str',
'char_str',
'char_str',
'c...
feature_types=None, gamma=None, gpu_id=None,
grow_policy=None, importance_type='gain',
interaction_constraints=None, learning_rate=None,
max_bin=None, max_cat_threshold=None,
max_cat_to_onehot=None, max_delta_step=None,
max_depth=3, max_leaves=None, min_child_weight=1,
missing=nan, monotone_constraints=None,
multi_strategy=None, n_estimators=100, n_jobs=4,
nthread=None, ...))])FeatureUnion(transformer_list=[('float32_transform_140705276704720',
Pipeline(steps=[('numpycolumnselector',
NumpyColumnSelector(columns=[0,
1,
2,
3,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19])),
('compressstrings',
CompressStrings(compress_type='hash',
dtypes_list=['char_str',
'float_int_num',
'char_str',
'char_str',
'char_str',
'char_str',
'float_int_num',
'char_s...
NumpyColumnSelector(columns=[4])),
('floatstr2float',
FloatStr2Float(dtypes_list=['float_int_num'],
missing_values_reference_list=[])),
('numpyreplacemissingvalues',
NumpyReplaceMissingValues(missing_values=[])),
('numimputer',
NumImputer(missing_values=nan,
strategy='median')),
('optstandardscaler',
OptStandardScaler(use_scaler_flag=False)),
('float32_transform',
float32_transform())]))])NumpyColumnSelector(columns=[0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19])CompressStrings(compress_type='hash',
dtypes_list=['char_str', 'float_int_num', 'char_str',
'char_str', 'char_str', 'char_str',
'float_int_num', 'char_str', 'char_str',
'float_int_num', 'char_str', 'float_int_num',
'char_str', 'char_str', 'float_int_num',
'char_str', 'float_int_num', 'char_str',
'char_str'],
missing_values_reference_list=['', '-', '?', nan],
misslist_list=[[], [], [], [], [], [], [], [], [], [], [], [],
[], [], [], [], [], [], []])NumpyReplaceMissingValues(missing_values=[])
NumpyReplaceUnknownValues(filling_values=nan,
filling_values_list=[nan, 100001, nan, nan, nan, nan,
100001, nan, nan, 100001, nan,
100001, nan, nan, 100001, nan,
100001, nan, nan],
known_values_list=[[227259264688753646810077375790908286508,
253732214910815238134509288111402486722,
303819144345098626554456011496217223575,
280353606872939388614315901186094326949],
[4.0, 5.0...
[328286527295663582663365503319902632676,
119641707607939038914465000864290288880,
283364312271660996400883763491949419861,
27741019508977055807423991753468819528],
[1.0, 2.0],
[68186749286663113704472210246844540664,
220736790854050750400968561922076059550],
[169662019754859674907370307324476606919,
220736790854050750400968561922076059550]],
missing_values_reference_list=['', '-', '?', nan])boolean2float()
CatImputer(missing_values=nan, strategy='most_frequent')
CatEncoder(categories='auto', dtype=<class 'numpy.float64'>, encoding='ordinal',
handle_unknown='error')float32_transform()
NumpyColumnSelector(columns=[4])
FloatStr2Float(dtypes_list=['float_int_num'], missing_values_reference_list=[])
NumpyReplaceMissingValues(missing_values=[])
NumImputer(missing_values=nan, strategy='median')
OptStandardScaler(use_scaler_flag=False)
float32_transform()
NumpyPermuteArray(axis=0,
permutation_indices=[0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 4])autoai_libs.cognito.transforms.transform_utils.TA1(fun = numpy.sqrt, name = 'sqrt', datatypes = ['numeric'], feat_constraints = [<cyfunction is_non_negative at 0x7ff878ab1220>, <cyfunction is_not_categorical at 0x7ff878ab1970>], tgraph = None, apply_all = True, col_names = ['CheckingStatus', 'LoanDuration', 'CreditHistory', 'LoanPurpose', 'LoanAmount', 'ExistingSavings', 'EmploymentDuration', 'InstallmentPercent', 'Sex', 'OthersOnLoan', 'CurrentResidenceDuration', 'OwnsProperty', 'Age', 'InstallmentPlans', 'Housing', 'ExistingCreditsCount', 'Job', 'Dependents', 'Telephone', 'ForeignWorker'], col_dtypes = [dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32')], col_as_json_objects = None)autoai_libs.cognito.transforms.transform_utils.FS1(cols_ids_must_keep = range(0, 20), additional_col_count_to_keep = 20, ptype = 'classification')
autoai_libs.cognito.transforms.transform_utils.TA1(fun = numpy.rint, name = 'round', datatypes = ['numeric'], feat_constraints = [<cyfunction is_not_categorical at 0x7ff878ab1970>], tgraph = None, apply_all = True, col_names = ['CheckingStatus', 'LoanDuration', 'CreditHistory', 'LoanPurpose', 'LoanAmount', 'ExistingSavings', 'EmploymentDuration', 'InstallmentPercent', 'Sex', 'OthersOnLoan', 'CurrentResidenceDuration', 'OwnsProperty', 'Age', 'InstallmentPlans', 'Housing', 'ExistingCreditsCount', 'Job', 'Dependents', 'Telephone', 'ForeignWorker', 'sqrt(LoanDuration)', 'sqrt(LoanAmount)', 'sqrt(Age)'], col_dtypes = [dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32'), dtype('float32')], col_as_json_objects = None)autoai_libs.cognito.transforms.transform_utils.FS1(cols_ids_must_keep = range(0, 20), additional_col_count_to_keep = 20, ptype = 'classification')
XGBClassifier(base_score=None, booster=None, callbacks=None,
colsample_bylevel=None, colsample_bynode=None,
colsample_bytree=None, device=None, early_stopping_rounds=None,
enable_categorical=False, eval_metric=None, feature_types=None,
gamma=None, gpu_id=None, grow_policy=None, importance_type='gain',
interaction_constraints=None, learning_rate=None, max_bin=None,
max_cat_threshold=None, max_cat_to_onehot=None,
max_delta_step=None, max_depth=3, max_leaves=None,
min_child_weight=1, missing=nan, monotone_constraints=None,
multi_strategy=None, n_estimators=100, n_jobs=4, nthread=None, ...)Each node in the visualization is a machine-learning operator (transformer or estimator). Each edge indicates data flow (transformed output from one operator becomes input to the next). The input to the root nodes is the initial dataset and the output from the sink node is the final prediction. When you hover the mouse pointer over a node, a tooltip shows you the configuration arguments of the corresponding operator (tuned hyperparameters). When you click on the hyperlink of a node, it brings you to a documentation page for the operator.
Test pipeline model locally¶
Read the data¶
data_connections = pipeline_optimizer.get_data_connections()
X_train, X_holdout, y_train, y_holdout = data_connections[0].read(
with_holdout_split=True
)
Calculate metrics¶
For detail description of used metrics you can check the documentation:
from lale.lib.aif360 import disparate_impact, accuracy_and_disparate_impact
from sklearn.metrics import accuracy_score
predicted_y = best_pipeline.predict(X_holdout.values)
disparate_impact_scorer = disparate_impact(**fairness_info)
accuracy_disparate_impact_scorer = accuracy_and_disparate_impact(**fairness_info)
print("Accuracy: {:.2f}".format(accuracy_score(y_true=y_holdout, y_pred=predicted_y)))
print(
"Disparate impact: {:.2f}".format(
disparate_impact_scorer(best_pipeline, X_holdout, y_holdout)
)
)
print(
"Accuracy and disparate impact: {:.2f}".format(
accuracy_disparate_impact_scorer(best_pipeline, X_holdout, y_holdout)
)
)
Accuracy: 0.81 Disparate impact: 1.46 Accuracy and disparate impact: 0.75
Fairness insights¶
You can analize favorable outcome distributions using visualize method from utils module.
from ibm_watsonx_ai.utils.autoai.fairness import visualize
visualize(run_details, pipeline_name)
Clean up¶
If you want to clean up all created assets:
- experiments
- trainings
- pipelines
- model definitions
- models
- functions
- deployments
please follow up this sample notebook.
Summary and next steps¶
You successfully completed this notebook!
As a next step you can deploy and score the model: Sample notebook.
Check out our Online Documentation for more samples, tutorials, documentation, how-tos, and blog posts.
Authors¶
Lukasz Cmielowski, PhD, is an Automation Architect and Data Scientist at IBM with a track record of developing enterprise-level applications that substantially increases clients' ability to turn data into actionable knowledge.
Dorota Lączak, Software Engineer at watsonx.ai.
Szymon Kucharczyk, Software Engineer at watsonx.ai.
Copyright © 2021-2025 IBM. This notebook and its source code are released under the terms of the MIT License.